package com.example.controller;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class OCRController {

    // 定义Tesseract训练库的路径
    private static final String TESSDATA_PATH = "C:/Users/lenovo/Desktop/OCR-demo/tessdata";

    @PostMapping("/upload")
    public Map<String, String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        Map<String, String> response = new HashMap<>();

        if (file.isEmpty()) {
            response.put("error", "File is empty");
            return response;
        }

        try {
            // 将上传的文件保存到本地
            String fileName = file.getOriginalFilename();
            File convFile = new File(System.getProperty("java.io.tmpdir") + "/" + fileName);
            file.transferTo(convFile);

            // 初始化Tesseract OCR
            ITesseract tesseract = new Tesseract();
            tesseract.setDatapath(TESSDATA_PATH); // 设置tessdata路径
            tesseract.setLanguage("chi_sim"); // 设置语言

            // 进行OCR识别
            String extractedText = tesseract.doOCR(convFile);

            // 返回提取到的文字
            response.put("extractedText", extractedText);

        } catch (IOException | TesseractException e) {
            e.printStackTrace();
            response.put("error", "Failed to process the file");
        }

        return response;
    }
}
